/*
 * BanBu_ChatToseePic
 * @description 本文件提供聊天界面点击图片放大展示的文件
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供聊天界面点击图片放大展示的文件
 */

#import "BanBu_ChatToseePic.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "BanBu_GraffitiController.h"
#import "WXOpen.h"
#import "ShareViewController.h"
#import "UIViewController+Animation.h"
#import "BanBu_UMengShareManager.h"
#import "QuadCurveMenu.h"

@interface BanBu_ChatToseePic (private)

-(void)fenxiang;


@end

@implementation BanBu_ChatToseePic

@synthesize shareArr=_shareArr;

-(void)dealloc{
    [_shortUrl release];_shortUrl = nil;
    self.shareArr = nil;
    [_assetLibrary release],_assetLibrary = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"dismissController" object:nil];
    [super dealloc];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 这是 右边的
    UIBarButtonItem *sendButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_topbar_more.png"] style:UIBarButtonItemStylePlain target:self action:@selector(addFun)] autorelease];
    // Set appearance
    if ([UIBarButtonItem respondsToSelector:@selector(addFun)]) {
        [sendButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        [sendButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsLandscapePhone];
        [sendButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
        [sendButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsLandscapePhone];
        [sendButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateNormal];
        [sendButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateHighlighted];
    }
    self.navigationItem.rightBarButtonItem = sendButton;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dismissController) name:@"dismissController" object:nil];
    //20141020
    //zyfzyfzyf⬇️
#warning 没有国际化
    _shortUrl=[[NSMutableString alloc]init];
    NSString *langauage=[MyAppDataManager getPreferredLanguage];
    if ([langauage isEqualToString:@"zh-Hans"]) {
        //sina
        QuadCurveMenuItem *sinaMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_sina_icon.png"] withIntro:NSLocalizedString(@"sinaPlatform", nil)];
        // tencentWeibo
        QuadCurveMenuItem *tencentMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_tencent_icon.png"] withIntro:NSLocalizedString(@"tencentPlatform", nil)];
        
        // qzone
        QuadCurveMenuItem *qzoneMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_qzone_icon.png"] withIntro:NSLocalizedString(@"qqZonePlatform", nil)];
        //wechatLine
        QuadCurveMenuItem *weLineMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_wechat_timeline_icon.png"] withIntro:NSLocalizedString(@"wechatTimelinePlatform", nil)];
        // wechatSession
        QuadCurveMenuItem *weSessionMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_wechat_session_icon.png"] withIntro:NSLocalizedString(@"wechatSessionPlatform", nil)];
        // renren
        QuadCurveMenuItem *renrenMenuItem= [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_renren_icon.png"] withIntro:NSLocalizedString(@"renrenPlatForm", nil)];
        
        //facebook
        QuadCurveMenuItem *FacebookMenuItem= [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_facebook_icon.png"] withIntro:@"Facebook"];
        //twitter
        QuadCurveMenuItem * TwitterItem= [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_twitter_icon.png"] withIntro:@"Twitter"];
        
        NSArray *menus = [NSArray arrayWithObjects:sinaMenuItem, tencentMenuItem, qzoneMenuItem, weLineMenuItem, weSessionMenuItem, renrenMenuItem,FacebookMenuItem,TwitterItem, nil];
        [FacebookMenuItem release];
        [TwitterItem release];
        [sinaMenuItem release];
        [qzoneMenuItem release];
        [tencentMenuItem release];
        [weLineMenuItem release];
        [weSessionMenuItem release];
        [renrenMenuItem release];
        
        _menu = [[QuadCurveMenu alloc] initWithFrame:CGRectMake(0, 0, __MainScreen_Width,  __MainScreen_Height+20 ) menus:menus withShare:YES];
        _menu.delegate = self;
        [self.view addSubview:_menu];
        
    }
    else
    {
        QuadCurveMenuItem *facebookMenuItem1 = [[QuadCurveMenuItem alloc] initWithCustomImage:nil withIntro:nil];
        facebookMenuItem1.userInteractionEnabled=NO;
        //facebook
        QuadCurveMenuItem *facebookMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"facebookForm.png"] withIntro:@"Facebook"];
        //twitter
        QuadCurveMenuItem *twitterMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"twitterForm.png"] withIntro:@"Twitter"];
        NSArray *menus = [NSArray arrayWithObjects:facebookMenuItem1,facebookMenuItem,facebookMenuItem1,facebookMenuItem1,twitterMenuItem, nil];
        [facebookMenuItem release];
        [twitterMenuItem release];
        _menu = [[QuadCurveMenu alloc] initWithFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height+20) menus:menus withShare:YES];
        _menu.delegate = self;
        [self.view addSubview:_menu];
        
    }
    //zyfzyfzyf⬆️
    //20141020
}

-(void)dismissController{
    [self dismissViewControllerAnimated:NO];
    
}

-(void)addFun{
    UIActionSheet *function;
    if(_type){
        //对话查看大图
        NSString *langauage=[MyAppDataManager getPreferredLanguage];
        if([langauage isEqual:@"zh-Hans"]){
            function = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"saveToAlum", nil),NSLocalizedString(@"tuyaReply", nil),NSLocalizedString(@"shareButton", nil), nil];
            
        }else{
            function = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"saveToAlum", nil),NSLocalizedString(@"tuyaReply", nil),NSLocalizedString(@"shareButton", nil), nil];
            
        }
        
    }else{
        //广播查看大图
        NSString *langauage=[MyAppDataManager getPreferredLanguage];
        if([langauage isEqual:@"zh-Hans"]){
            function = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"saveToAlum", nil),NSLocalizedString(@"tuyaEdit", nil),NSLocalizedString(@"shareButton", nil), nil];
            
        }else{
            function = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"saveToAlum", nil),NSLocalizedString(@"tuyaEdit", nil),NSLocalizedString(@"shareButton", nil), nil];
            
        }
        
    }
    
    function.tag = 1;
    [function showInView:self.view];
    [function release];
    
}

//zyfzyfzyf⬇️
#pragma mark HUDDelegate
-(void)hudWasHidden:(MBProgressHUD *)hud
{
    [hud removeFromSuperview];
    [hud release];
    hud=nil;
}
#pragma mark quadCurveMenuDelegate
-(void)quadCurveMenu:(QuadCurveMenu *)menu didSelectIndex:(NSInteger)idx
{
    [_menu setExpanding:NO];
    
    _hud=[[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:_hud];
    _hud.labelText=NSLocalizedString(@"loadingNotice", nil);
    _hud.delegate=self;
    [_hud show:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *sayText=[NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"koochatComment", nil),_shortUrl];
        UIImage *shareImg=[_shareArr objectAtIndex:0];
        NSString *urlStr=[_shareArr objectAtIndex:1];
        dispatch_async(dispatch_get_main_queue(), ^{
            [_hud hide:YES];
            NSString *langauage=[MyAppDataManager getPreferredLanguage];
            if ([langauage isEqualToString:@"zh-Hans"]) {
                [[BanBu_UMengShareManager shareUMengManager] shareToPlatform:idx WithText:sayText WithImage:shareImg WithClickUrlStr:urlStr WithPerformVC:self];
            }
            else
            {
                if (idx==1) {
                    [[BanBu_UMengShareManager shareUMengManager] shareToPlatform:6 WithText:sayText WithImage:shareImg WithClickUrlStr:urlStr WithPerformVC:self];
                }
                else
                    [[BanBu_UMengShareManager shareUMengManager] shareToPlatform:7 WithText:sayText WithImage:shareImg WithClickUrlStr:urlStr WithPerformVC:self];
                
            }
            
        });
        
    });
    
}
//zyfzyfzyf⬆️


#pragma mark - UIActionSheetDelegate

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(actionSheet.tag == 1){
        if(buttonIndex == 0){
            if(!_assetLibrary){
                _assetLibrary = [[ALAssetsLibrary alloc]init];
            }
            [_assetLibrary saveImage:[self.shareArr objectAtIndex:0] toAlbum:NSLocalizedString(@"fristTitle", nil) completionBlock:^(NSURL *assetURL, NSError *error) {
                
                [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"savesucess", nil) activityAnimated:NO duration:2.0];
                
            } failureBlock:^(NSError *error) {
                
                [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"savefail", nil) activityAnimated:NO duration:2.0];
            }];
        }
        else if(buttonIndex == 1){
            BanBu_GraffitiController *aGraff=[[BanBu_GraffitiController alloc]initWithImage:[self.shareArr objectAtIndex:0] andSourceType:_type];
            [self.navigationController pushViewController:aGraff animated:YES];
            //            [self presentViewController:aGraff animated:YES];
            [aGraff release];
        }
        else if (buttonIndex ==2)
        {//分享
            [_menu setExpanding:YES];
            self.navigationController.navigationBar.alpha=0;
            NSString * shareUrl = [NSString stringWithFormat:@"%@",[_shareArr objectAtIndex:1]];
            [AppComManager getBanBuData:@"/_sys_dict/_get_short_url.php?jsonfrom=" par:[NSDictionary dictionaryWithObjectsAndKeys:shareUrl,@"url", nil] delegate:self];
            
            
        }
        
    }
    
}


- (void) performPublishAction:(void (^)(void)) action {
    // we defer request for permission to post to the moment of post, then we check for the permission
    if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound) {
        // if we don't already have the permission, then we request it now
        [FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:@"publish_actions"]
                                                   defaultAudience:FBSessionDefaultAudienceFriends
                                                 completionHandler:^(FBSession *session, NSError *error) {
                                                     if (!error) {
                                                         [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sendingNotice", nil) activityAnimated:YES];
                                                         
                                                         action();
                                                     }
                                                     //For this example, ignore errors (such as if user cancels).
                                                 }];
    } else {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sendingNotice", nil) activityAnimated:YES];
        
        action();
    }
    
}
- (void)showAlert:(NSString *)message
           result:(id)result
            error:(NSError *)error {
    
    NSString *alertMsg;
    NSString *alertTitle;
    if (error) {
        alertMsg = error.localizedDescription;
        alertTitle = @"Error";
    } else {
        NSDictionary *resultDict = (NSDictionary *)result;
        alertMsg = [NSString stringWithFormat:@"Successfully posted '%@'.\nPost ID: %@",
                    message, [resultDict valueForKey:@"id"]];
        alertTitle = @"Success";
    }
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
                                                        message:alertMsg
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    
    
    TKLoadingView *indictor = nil;
    for(indictor in self.view.subviews)
        if([indictor isKindOfClass:[TKLoadingView class]])
        {
            [indictor setActivityAnimating:NO withShowMsg:NSLocalizedString(@"shareSuccess", nil)];
            [indictor dismissAfterDelay:1.0 animated:YES];
        }
    
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    
    TKLoadingView *indictor = nil;
    for(indictor in self.view.subviews)
        if([indictor isKindOfClass:[TKLoadingView class]])
        {
            [indictor setActivityAnimating:NO withShowMsg:NSLocalizedString(@"errcode_fail", nil)];
            [indictor dismissAfterDelay:1.0 animated:YES];
        }
}

- (void)storeAccessToken:(NSString *)accessToken {
    [[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:@"SavedAccessHTTPBody"];
}

- (NSString *)loadAccessToken {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SavedAccessHTTPBody"];
}
#pragma mark - requestFinish
//20141020
-(void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    if ([[resDic valueForKey:@"fc"] isEqualToString:@"get_short_url"]) {
        _shortUrl=[resDic valueForKey:@"shorturl"];
        [_shortUrl retain];
    }
}
//20141020
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
